Through PEP 695, Python 3.12 introduces the type parameter syntax to allow for a more compact and
explicit way to define generic classes and functions.
Prior to Python 3.12, defining a generic class would be done through the following syntax:
from typing import Generic, TypeVar
_T_co = TypeVar("_T_co", covariant=True, bound=str)
class ClassA(Generic[_T_co]):
def method1(self) -> _T_co:
...
Since Python 3.12, it can be done with the following syntax:
class ClassA[T: str]:
def method1(self) -> T:
...
Using the former syntax requires importing TypeVar
and Generic
symbols from the typing
module. It also
requires the explicit definition of a type variable in the global scope, with a redundant name provided in quotes (T = TypeVar("T")
).
This makes the definition of generic classes verbose and confusing.
It is therefore recommended to use the type parameter syntax when working with Python 3.12 and later.
Exceptions
This rule will only raise an issue when the Python version of the analyzed project is set to 3.12 or higher.